package cn.tedu.msmservice.controller;

import cn.hutool.core.util.RandomUtil;
import cn.tedu.commonUtils.R;
import cn.tedu.msmservice.service.MsmService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm")
@CrossOrigin
@Slf4j
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return R.ok();

       code = RandomUtil.randomNumbers(6);
        log.info("验证码：{}",code);
        boolean isSend = msmService.send(phone, code);
        if(isSend) {
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok().msg("短信发送成功");
        } else {
            return R.error().msg("发送短信失败");
        }
    }
}
